# coding:utf8
from flask import Flask, redirect, url_for, request, render_template, jsonify, Response
import json
import datetime
import time
import openai

MSG_FILE = "message_都问些什么问题.txt"

app = Flask(__name__)
openai.api_key = "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"

messages = []


@app.route('/')
def index():
    return render_template("index.html")


@app.route('/ask_chatgpt_35_stream/', methods=['POST', 'GET'])
def ask_chatgpt_35_stream():
    """ChatGPT Prompt"""
    # message = request.json.get('message', '')
    data = request.get_data()
    # print(data)
    data = json.loads(data)

    # model = data["model"]
    message = data["message"]

    with open(MSG_FILE, 'a', encoding='utf-8') as f:
        f.write("[{}] {}\n".format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), message))

    # message = "2乘2"
    messages.append(
        {"role": "user", "content": message},
    )
    response = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",
        messages=messages,
        # temperature=0.7,
        stream=True,
        # timeout=20
    )

    def generate():
        ts = ''
        for trunk in response:

            # print(5, trunk['choices'][0]['delta'])
            if trunk['choices'][0]['delta']:
                # print(5, trunk['choices'][0]['delta']['content'])
                ts += trunk['choices'][0]['delta']['content']
                yield trunk['choices'][0]['delta']['content'] + '\n'
            else:
                ts += '\n'
                # print(ts)
                yield "\n"

    headers = {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'X-Accel-Buffering': 'no',
    }
    return Response(generate(), mimetype="text/event-stream", headers=headers)


@app.route('/ask_chatgpt_35/', methods=['POST', 'GET'])
def ask_chatgpt_35():
    if request.method == 'POST':
        # print(1)
        data = request.get_data()
        # print(data)
        data = json.loads(data)

        model = data["model"]
        message = data["message"]

        with open(MSG_FILE, 'a', encoding='utf-8') as f:
            f.write("[{}] {}\n".format(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"), message))

        messages.append(
            {"role": "user", "content": message},
        )
        chat = openai.ChatCompletion.create(
            model=model, messages=messages
        )
        reply = chat.choices[0].message.content
        print(f"ChatGPT: {reply}")
        messages.append({"role": "assistant", "content": reply})

        return {"reply_content": reply, "finish_reason": "stop"}


if __name__ == '__main__':
    # app.run(debug=False, host='0.0.0.0', port=int("8003"))
    app.run(debug=True, host='0.0.0.0', port=int("8003"))
    # app.run(debug=True, host='127.0.0.1', port=int("80"),)
    # app.run(debug=True)
